1   /*                        __    __  __  __    __  ___
2    *                       \  \  /  /    \  \  /  /  __/
3    *                        \  \/  /  /\  \  \/  /  /
4    *                         \____/__/  \__\____/__/.ɪᴏ
5    * ᶜᵒᵖʸʳᶦᵍʰᵗ ᵇʸ ᵛᵃᵛʳ ⁻ ˡᶦᶜᵉⁿˢᵉᵈ ᵘⁿᵈᵉʳ ᵗʰᵉ ᵃᵖᵃᶜʰᵉ ˡᶦᶜᵉⁿˢᵉ ᵛᵉʳˢᶦᵒⁿ ᵗʷᵒ ᵈᵒᵗ ᶻᵉʳᵒ
6    */
7   package io.vavr.collection;
8   
9   import io.vavr.*;
10  import io.vavr.collection.VectorModule.Combinations;
11  import io.vavr.control.Option;
12  
13  import java.io.Serializable;
14  import java.util.*;
15  import java.util.function.*;
16  import java.util.stream.Collector;
17  
18  import static io.vavr.collection.Collections.withSize;
19  import static io.vavr.collection.JavaConverters.ChangePolicy.IMMUTABLE;
20  import static io.vavr.collection.JavaConverters.ChangePolicy.MUTABLE;
21  
22  /**
23   * Vector is the default Seq implementation that provides effectively constant time access to any element.
24   * Many other operations (e.g. `tail`, `drop`, `slice`) are also effectively constant.
25   *
26   * The implementation is based on a `bit-mapped trie`, a very wide and shallow tree (i.e. depth ≤ 6).
27   *
28   * @param <T> Component type of the Vector.
29   * @author Ruslan Sennov, Pap Lőrinc
30   */
31  public final class Vector<T> implements IndexedSeq<T>, Serializable {
32      private static final long serialVersionUID = 1L;
33  
34      private static final Vector<?> EMPTY = new Vector<>(BitMappedTrie.empty());
35  
36      final BitMappedTrie<T> trie;
37      private Vector(BitMappedTrie<T> trie) { this.trie = trie; }
38  
39      @SuppressWarnings("ObjectEquality")
40      private Vector<T> wrap(BitMappedTrie<T> trie) {
41          return (trie == this.trie)
42                 ? this
43                 : ofAll(trie);
44      }
45  
46      private static <T> Vector<T> ofAll(BitMappedTrie<T> trie) {
47          return (trie.length() == 0)
48                 ? empty()
49                 : new Vector<>(trie);
50      }
51  
52      /**
53       * Returns the empty Vector.
54       *
55       * @param <T> Component type.
56       * @return The empty Vector.
57       */
58      @SuppressWarnings("unchecked")
59      public static <T> Vector<T> empty() { return (Vector<T>) EMPTY; }
60  
61      /**
62       * Returns a {@link Collector} which may be used in conjunction with
63       * {@link java.util.stream.Stream#collect(Collector)} to obtain a {@link Vector}.
64       *
65       * @param <T> Component type of the Vector.
66       * @return A io.vavr.collection.List Collector.
67       */
68      public static <T> Collector<T, ArrayList<T>, Vector<T>> collector() {
69          final Supplier<ArrayList<T>> supplier = ArrayList::new;
70          final BiConsumer<ArrayList<T>, T> accumulator = ArrayList::add;
71          final BinaryOperator<ArrayList<T>> combiner = (left, right) -> {
72              left.addAll(right);
73              return left;
74          };
75          final Function<ArrayList<T>, Vector<T>> finisher = Vector::ofAll;
76          return Collector.of(supplier, accumulator, combiner, finisher);
77      }
78  
79      /**
80       * Narrows a widened {@code Vector<? extends T>} to {@code Vector<T>}
81       * by performing a type-safe cast. This is eligible because immutable/read-only
82       * collections are covariant.
83       *
84       * @param vector An {@code Vector}.
85       * @param <T>    Component type of the {@code Vector}.
86       * @return the given {@code vector} instance as narrowed type {@code Vector<T>}.
87       */
88      @SuppressWarnings("unchecked")
89      public static <T> Vector<T> narrow(Vector<? extends T> vector) { return (Vector<T>) vector; }
90  
91      /**
92       * Returns a singleton {@code Vector}, i.e. a {@code Vector} of one element.
93       *
94       * @param element An element.
95       * @param <T>     The component type
96       * @return A new Vector instance containing the given element
97       */
98      public static <T> Vector<T> of(T element) {
99          return ofAll(Iterator.of(element));
100     }
101 
102     /**
103      * Creates a Vector of the given elements.
104      *
105      * @param <T>      Component type of the Vector.
106      * @param elements Zero or more elements.
107      * @return A vector containing the given elements in the same order.
108      * @throws NullPointerException if {@code elements} is null
109      */
110     @SafeVarargs
111     @SuppressWarnings("varargs")
112     public static <T> Vector<T> of(T... elements) {
113         Objects.requireNonNull(elements, "elements is null");
114         return ofAll(BitMappedTrie.ofAll(elements));
115     }
116 
117     /**
118      * Returns a Vector containing {@code n} values of a given Function {@code f}
119      * over a range of integer values from 0 to {@code n - 1}.
120      *
121      * @param <T> Component type of the Vector
122      * @param n   The number of elements in the Vector
123      * @param f   The Function computing element values
124      * @return A Vector consisting of elements {@code f(0),f(1), ..., f(n - 1)}
125      * @throws NullPointerException if {@code f} is null
126      */
127     public static <T> Vector<T> tabulate(int n, Function<? super Integer, ? extends T> f) {
128         Objects.requireNonNull(f, "f is null");
129         return io.vavr.collection.Collections.tabulate(n, f, empty(), Vector::of);
130     }
131 
132     /**
133      * Returns a Vector containing {@code n} values supplied by a given Supplier {@code s}.
134      *
135      * @param <T> Component type of the Vector
136      * @param n   The number of elements in the Vector
137      * @param s   The Supplier computing element values
138      * @return A Vector of size {@code n}, where each element contains the result supplied by {@code s}.
139      * @throws NullPointerException if {@code s} is null
140      */
141     public static <T> Vector<T> fill(int n, Supplier<? extends T> s) {
142         Objects.requireNonNull(s, "s is null");
143         return io.vavr.collection.Collections.fill(n, s, empty(), Vector::of);
144     }
145 
146     /**
147      * Creates a Vector of the given elements.
148      * <p>
149      * The resulting vector has the same iteration order as the given iterable of elements
150      * if the iteration order of the elements is stable.
151      *
152      * @param <T>      Component type of the Vector.
153      * @param iterable An Iterable of elements.
154      * @return A vector containing the given elements in the same order.
155      * @throws NullPointerException if {@code elements} is null
156      */
157     @SuppressWarnings("unchecked")
158     public static <T> Vector<T> ofAll(Iterable<? extends T> iterable) {
159         Objects.requireNonNull(iterable, "iterable is null");
160         if (iterable instanceof Vector) {
161             return (Vector<T>) iterable;
162         } else {
163             final Object[] values = withSize(iterable).toArray();
164             return ofAll(BitMappedTrie.ofAll(values));
165         }
166     }
167 
168     /**
169      * Creates a Vector that contains the elements of the given {@link java.util.stream.Stream}.
170      *
171      * @param javaStream A {@link java.util.stream.Stream}
172      * @param <T>        Component type of the Stream.
173      * @return A Vector containing the given elements in the same order.
174      */
175     public static <T> Vector<T> ofAll(java.util.stream.Stream<? extends T> javaStream) {
176         Objects.requireNonNull(javaStream, "javaStream is null");
177         return ofAll(Iterator.ofAll(javaStream.iterator()));
178     }
179 
180     /**
181      * Creates a Vector from boolean values.
182      *
183      * @param elements boolean values
184      * @return A new Vector of Boolean values
185      * @throws NullPointerException if elements is null
186      */
187     public static Vector<Boolean> ofAll(boolean... elements) {
188         Objects.requireNonNull(elements, "elements is null");
189         return ofAll(BitMappedTrie.ofAll(elements));
190     }
191 
192     /**
193      * Creates a Vector from byte values.
194      *
195      * @param elements byte values
196      * @return A new Vector of Byte values
197      * @throws NullPointerException if elements is null
198      */
199     public static Vector<Byte> ofAll(byte... elements) {
200         Objects.requireNonNull(elements, "elements is null");
201         return ofAll(BitMappedTrie.ofAll(elements));
202     }
203 
204     /**
205      * Creates a Vector from char values.
206      *
207      * @param elements char values
208      * @return A new Vector of Character values
209      * @throws NullPointerException if elements is null
210      */
211     public static Vector<Character> ofAll(char... elements) {
212         Objects.requireNonNull(elements, "elements is null");
213         return ofAll(BitMappedTrie.ofAll(elements));
214     }
215 
216     /**
217      * Creates a Vector from double values.
218      *
219      * @param elements double values
220      * @return A new Vector of Double values
221      * @throws NullPointerException if elements is null
222      */
223     public static Vector<Double> ofAll(double... elements) {
224         Objects.requireNonNull(elements, "elements is null");
225         return ofAll(BitMappedTrie.ofAll(elements));
226     }
227 
228     /**
229      * Creates a Vector from float values.
230      *
231      * @param elements float values
232      * @return A new Vector of Float values
233      * @throws NullPointerException if elements is null
234      */
235     public static Vector<Float> ofAll(float... elements) {
236         Objects.requireNonNull(elements, "elements is null");
237         return ofAll(BitMappedTrie.ofAll(elements));
238     }
239 
240     /**
241      * Creates a Vector from int values.
242      *
243      * @param elements int values
244      * @return A new Vector of Integer values
245      * @throws NullPointerException if elements is null
246      */
247     public static Vector<Integer> ofAll(int... elements) {
248         Objects.requireNonNull(elements, "elements is null");
249         return ofAll(BitMappedTrie.ofAll(elements));
250     }
251 
252     /**
253      * Creates a Vector from long values.
254      *
255      * @param elements long values
256      * @return A new Vector of Long values
257      * @throws NullPointerException if elements is null
258      */
259     public static Vector<Long> ofAll(long... elements) {
260         Objects.requireNonNull(elements, "elements is null");
261         return ofAll(BitMappedTrie.ofAll(elements));
262     }
263 
264     /**
265      * Creates a Vector from short values.
266      *
267      * @param elements short values
268      * @return A new Vector of Short values
269      * @throws NullPointerException if elements is null
270      */
271     public static Vector<Short> ofAll(short... elements) {
272         Objects.requireNonNull(elements, "elements is null");
273         return ofAll(BitMappedTrie.ofAll(elements));
274     }
275 
276     public static Vector<Character> range(char from, char toExclusive) {
277         return ofAll(ArrayType.<char[]> asPrimitives(char.class, Iterator.range(from, toExclusive)));
278     }
279 
280     public static Vector<Character> rangeBy(char from, char toExclusive, int step) {
281         return ofAll(ArrayType.<char[]> asPrimitives(char.class, Iterator.rangeBy(from, toExclusive, step)));
282     }
283 
284     @GwtIncompatible
285     public static Vector<Double> rangeBy(double from, double toExclusive, double step) {
286         return ofAll(ArrayType.<double[]> asPrimitives(double.class, Iterator.rangeBy(from, toExclusive, step)));
287     }
288 
289     /**
290      * Creates a Vector of int numbers starting from {@code from}, extending to {@code toExclusive - 1}.
291      * <p>
292      * Examples:
293      * <pre>
294      * <code>
295      * Vector.range(0, 0)  // = Vector()
296      * Vector.range(2, 0)  // = Vector()
297      * Vector.range(-2, 2) // = Vector(-2, -1, 0, 1)
298      * </code>
299      * </pre>
300      *
301      * @param from        the first number
302      * @param toExclusive the last number + 1
303      * @return a range of int values as specified or the empty range if {@code from >= toExclusive}
304      */
305     public static Vector<Integer> range(int from, int toExclusive) {
306         return ofAll(ArrayType.<int[]> asPrimitives(int.class, Iterator.range(from, toExclusive)));
307     }
308 
309     /**
310      * Creates a Vector of int numbers starting from {@code from}, extending to {@code toExclusive - 1},
311      * with {@code step}.
312      * <p>
313      * Examples:
314      * <pre>
315      * <code>
316      * Vector.rangeBy(1, 3, 1)  // = Vector(1, 2)
317      * Vector.rangeBy(1, 4, 2)  // = Vector(1, 3)
318      * Vector.rangeBy(4, 1, -2) // = Vector(4, 2)
319      * Vector.rangeBy(4, 1, 2)  // = Vector()
320      * </code>
321      * </pre>
322      *
323      * @param from        the first number
324      * @param toExclusive the last number + 1
325      * @param step        the step
326      * @return a range of long values as specified or the empty range if<br>
327      * {@code from >= toInclusive} and {@code step > 0} or<br>
328      * {@code from <= toInclusive} and {@code step < 0}
329      * @throws IllegalArgumentException if {@code step} is zero
330      */
331     public static Vector<Integer> rangeBy(int from, int toExclusive, int step) {
332         return ofAll(ArrayType.<int[]> asPrimitives(int.class, Iterator.rangeBy(from, toExclusive, step)));
333     }
334 
335     /**
336      * Creates a Vector of long numbers starting from {@code from}, extending to {@code toExclusive - 1}.
337      * <p>
338      * Examples:
339      * <pre>
340      * <code>
341      * Vector.range(0L, 0L)  // = Vector()
342      * Vector.range(2L, 0L)  // = Vector()
343      * Vector.range(-2L, 2L) // = Vector(-2L, -1L, 0L, 1L)
344      * </code>
345      * </pre>
346      *
347      * @param from        the first number
348      * @param toExclusive the last number + 1
349      * @return a range of long values as specified or the empty range if {@code from >= toExclusive}
350      */
351     public static Vector<Long> range(long from, long toExclusive) {
352         return ofAll(ArrayType.<long[]> asPrimitives(long.class, Iterator.range(from, toExclusive)));
353     }
354 
355     /**
356      * Creates a Vector of long numbers starting from {@code from}, extending to {@code toExclusive - 1},
357      * with {@code step}.
358      * <p>
359      * Examples:
360      * <pre>
361      * <code>
362      * Vector.rangeBy(1L, 3L, 1L)  // = Vector(1L, 2L)
363      * Vector.rangeBy(1L, 4L, 2L)  // = Vector(1L, 3L)
364      * Vector.rangeBy(4L, 1L, -2L) // = Vector(4L, 2L)
365      * Vector.rangeBy(4L, 1L, 2L)  // = Vector()
366      * </code>
367      * </pre>
368      *
369      * @param from        the first number
370      * @param toExclusive the last number + 1
371      * @param step        the step
372      * @return a range of long values as specified or the empty range if<br>
373      * {@code from >= toInclusive} and {@code step > 0} or<br>
374      * {@code from <= toInclusive} and {@code step < 0}
375      * @throws IllegalArgumentException if {@code step} is zero
376      */
377     public static Vector<Long> rangeBy(long from, long toExclusive, long step) {
378         return ofAll(ArrayType.<long[]> asPrimitives(long.class, Iterator.rangeBy(from, toExclusive, step)));
379     }
380 
381     public static Vector<Character> rangeClosed(char from, char toInclusive) {
382         return ofAll(ArrayType.<char[]> asPrimitives(char.class, Iterator.rangeClosed(from, toInclusive)));
383     }
384 
385     public static Vector<Character> rangeClosedBy(char from, char toInclusive, int step) {
386         return ofAll(ArrayType.<char[]> asPrimitives(char.class, Iterator.rangeClosedBy(from, toInclusive, step)));
387     }
388 
389     @GwtIncompatible
390     public static Vector<Double> rangeClosedBy(double from, double toInclusive, double step) {
391         return ofAll(ArrayType.<double[]> asPrimitives(double.class, Iterator.rangeClosedBy(from, toInclusive, step)));
392     }
393 
394     /**
395      * Creates a Vector of int numbers starting from {@code from}, extending to {@code toInclusive}.
396      * <p>
397      * Examples:
398      * <pre>
399      * <code>
400      * Vector.rangeClosed(0, 0)  // = Vector(0)
401      * Vector.rangeClosed(2, 0)  // = Vector()
402      * Vector.rangeClosed(-2, 2) // = Vector(-2, -1, 0, 1, 2)
403      * </code>
404      * </pre>
405      *
406      * @param from        the first number
407      * @param toInclusive the last number
408      * @return a range of int values as specified or the empty range if {@code from > toInclusive}
409      */
410     public static Vector<Integer> rangeClosed(int from, int toInclusive) {
411         return ofAll(ArrayType.<int[]> asPrimitives(int.class, Iterator.rangeClosed(from, toInclusive)));
412     }
413 
414     /**
415      * Creates a Vector of int numbers starting from {@code from}, extending to {@code toInclusive},
416      * with {@code step}.
417      * <p>
418      * Examples:
419      * <pre>
420      * <code>
421      * Vector.rangeClosedBy(1, 3, 1)  // = Vector(1, 2, 3)
422      * Vector.rangeClosedBy(1, 4, 2)  // = Vector(1, 3)
423      * Vector.rangeClosedBy(4, 1, -2) // = Vector(4, 2)
424      * Vector.rangeClosedBy(4, 1, 2)  // = Vector()
425      * </code>
426      * </pre>
427      *
428      * @param from        the first number
429      * @param toInclusive the last number
430      * @param step        the step
431      * @return a range of int values as specified or the empty range if<br>
432      * {@code from > toInclusive} and {@code step > 0} or<br>
433      * {@code from < toInclusive} and {@code step < 0}
434      * @throws IllegalArgumentException if {@code step} is zero
435      */
436     public static Vector<Integer> rangeClosedBy(int from, int toInclusive, int step) {
437         return ofAll(ArrayType.<int[]> asPrimitives(int.class, Iterator.rangeClosedBy(from, toInclusive, step)));
438     }
439 
440     /**
441      * Creates a Vector of long numbers starting from {@code from}, extending to {@code toInclusive}.
442      * <p>
443      * Examples:
444      * <pre>
445      * <code>
446      * Vector.rangeClosed(0L, 0L)  // = Vector(0L)
447      * Vector.rangeClosed(2L, 0L)  // = Vector()
448      * Vector.rangeClosed(-2L, 2L) // = Vector(-2L, -1L, 0L, 1L, 2L)
449      * </code>
450      * </pre>
451      *
452      * @param from        the first number
453      * @param toInclusive the last number
454      * @return a range of long values as specified or the empty range if {@code from > toInclusive}
455      */
456     public static Vector<Long> rangeClosed(long from, long toInclusive) {
457         return ofAll(ArrayType.<long[]> asPrimitives(long.class, Iterator.rangeClosed(from, toInclusive)));
458     }
459 
460     /**
461      * Creates a Vector of long numbers starting from {@code from}, extending to {@code toInclusive},
462      * with {@code step}.
463      * <p>
464      * Examples:
465      * <pre>
466      * <code>
467      * Vector.rangeClosedBy(1L, 3L, 1L)  // = Vector(1L, 2L, 3L)
468      * Vector.rangeClosedBy(1L, 4L, 2L)  // = Vector(1L, 3L)
469      * Vector.rangeClosedBy(4L, 1L, -2L) // = Vector(4L, 2L)
470      * Vector.rangeClosedBy(4L, 1L, 2L)  // = Vector()
471      * </code>
472      * </pre>
473      *
474      * @param from        the first number
475      * @param toInclusive the last number
476      * @param step        the step
477      * @return a range of int values as specified or the empty range if<br>
478      * {@code from > toInclusive} and {@code step > 0} or<br>
479      * {@code from < toInclusive} and {@code step < 0}
480      * @throws IllegalArgumentException if {@code step} is zero
481      */
482     public static Vector<Long> rangeClosedBy(long from, long toInclusive, long step) {
483         return ofAll(ArrayType.<long[]> asPrimitives(long.class, Iterator.rangeClosedBy(from, toInclusive, step)));
484     }
485 
486     /**
487      * Transposes the rows and columns of a {@link Vector} matrix.
488      *
489      * @param <T> matrix element type
490      * @param matrix to be transposed.
491      * @return a transposed {@link Vector} matrix.
492      * @throws IllegalArgumentException if the row lengths of {@code matrix} differ.
493      * <p>
494      * ex: {@code
495      * Vector.transpose(Vector(Vector(1,2,3), Vector(4,5,6))) → Vector(Vector(1,4), Vector(2,5), Vector(3,6))
496      * }
497      */
498     public static <T> Vector<Vector<T>> transpose(Vector<Vector<T>> matrix) {
499         return io.vavr.collection.Collections.transpose(matrix, Vector::ofAll, Vector::of);
500     }
501 
502     /**
503      * Creates a Vector from a seed value and a function.
504      * The function takes the seed at first.
505      * The function should return {@code None} when it's
506      * done generating the Vector, otherwise {@code Some} {@code Tuple}
507      * of the element for the next call and the value to add to the
508      * resulting Vector.
509      * <p>
510      * Example:
511      * <pre>
512      * <code>
513      * Vector.unfoldRight(10, x -&gt; x == 0
514      *             ? Option.none()
515      *             : Option.of(new Tuple2&lt;&gt;(x, x-1)));
516      * // Vector(10, 9, 8, 7, 6, 5, 4, 3, 2, 1))
517      * </code>
518      * </pre>
519      *
520      * @param <T>  type of seeds
521      * @param <U>  type of unfolded values
522      * @param seed the start value for the iteration
523      * @param f    the function to get the next step of the iteration
524      * @return a Vector with the values built up by the iteration
525      * @throws NullPointerException if {@code f} is null
526      */
527     public static <T, U> Vector<U> unfoldRight(T seed, Function<? super T, Option<Tuple2<? extends U, ? extends T>>> f) {
528         return Iterator.unfoldRight(seed, f).toVector();
529     }
530 
531     /**
532      * Creates a Vector from a seed value and a function.
533      * The function takes the seed at first.
534      * The function should return {@code None} when it's
535      * done generating the Vector, otherwise {@code Some} {@code Tuple}
536      * of the value to add to the resulting Vector and
537      * the element for the next call.
538      * <p>
539      * Example:
540      * <pre>
541      * <code>
542      * Vector.unfoldLeft(10, x -&gt; x == 0
543      *             ? Option.none()
544      *             : Option.of(new Tuple2&lt;&gt;(x-1, x)));
545      * // Vector(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
546      * </code>
547      * </pre>
548      *
549      * @param <T>  type of seeds
550      * @param <U>  type of unfolded values
551      * @param seed the start value for the iteration
552      * @param f    the function to get the next step of the iteration
553      * @return a Vector with the values built up by the iteration
554      * @throws NullPointerException if {@code f} is null
555      */
556     public static <T, U> Vector<U> unfoldLeft(T seed, Function<? super T, Option<Tuple2<? extends T, ? extends U>>> f) {
557         return Iterator.unfoldLeft(seed, f).toVector();
558     }
559 
560     /**
561      * Creates a Vector from a seed value and a function.
562      * The function takes the seed at first.
563      * The function should return {@code None} when it's
564      * done generating the Vector, otherwise {@code Some} {@code Tuple}
565      * of the value to add to the resulting Vector and
566      * the element for the next call.
567      * <p>
568      * Example:
569      * <pre>
570      * <code>
571      * Vector.unfold(10, x -&gt; x == 0
572      *             ? Option.none()
573      *             : Option.of(new Tuple2&lt;&gt;(x-1, x)));
574      * // Vector(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
575      * </code>
576      * </pre>
577      *
578      * @param <T>  type of seeds and unfolded values
579      * @param seed the start value for the iteration
580      * @param f    the function to get the next step of the iteration
581      * @return a Vector with the values built up by the iteration
582      * @throws NullPointerException if {@code f} is null
583      */
584     public static <T> Vector<T> unfold(T seed, Function<? super T, Option<Tuple2<? extends T, ? extends T>>> f) {
585         return Iterator.unfold(seed, f).toVector();
586     }
587 
588     @Override
589     public Vector<T> append(T element) { return appendAll(io.vavr.collection.List.of(element)); }
590 
591     @Override
592     public Vector<T> appendAll(Iterable<? extends T> iterable) {
593         Objects.requireNonNull(iterable, "iterable is null");
594         if (isEmpty()) {
595             return ofAll(iterable);
596         } else {
597             final BitMappedTrie<T> that = trie.appendAll(iterable);
598             return (that == trie) ? this : new Vector<>(that);
599         }
600     }
601 
602     @Override
603     public java.util.List<T> asJava() {
604         return JavaConverters.asJava(this, IMMUTABLE);
605     }
606 
607     @Override
608     public Vector<T> asJava(Consumer<? super java.util.List<T>> action) {
609         return Collections.asJava(this, action, IMMUTABLE);
610     }
611 
612     @Override
613     public java.util.List<T> asJavaMutable() {
614         return JavaConverters.asJava(this, MUTABLE);
615     }
616 
617     @Override
618     public Vector<T> asJavaMutable(Consumer<? super java.util.List<T>> action) {
619         return Collections.asJava(this, action, MUTABLE);
620     }
621     
622     @Override
623     public <R> Vector<R> collect(PartialFunction<? super T, ? extends R> partialFunction) {
624         return ofAll(iterator().<R> collect(partialFunction));
625     }
626 
627     @Override
628     public Vector<Vector<T>> combinations() { return rangeClosed(0, length()).map(this::combinations).flatMap(Function.identity()); }
629 
630     @Override
631     public Vector<Vector<T>> combinations(int k) { return Combinations.apply(this, Math.max(k, 0)); }
632 
633     @Override
634     public Iterator<Vector<T>> crossProduct(int power) { return io.vavr.collection.Collections.crossProduct(empty(), this, power); }
635 
636     @Override
637     public Vector<T> distinct() { return distinctBy(Function.identity()); }
638 
639     @Override
640     public Vector<T> distinctBy(Comparator<? super T> comparator) {
641         Objects.requireNonNull(comparator, "comparator is null");
642         final java.util.Set<T> seen = new java.util.TreeSet<>(comparator);
643         return filter(seen::add);
644     }
645 
646     @Override
647     public <U> Vector<T> distinctBy(Function<? super T, ? extends U> keyExtractor) {
648         Objects.requireNonNull(keyExtractor, "keyExtractor is null");
649         final java.util.Set<U> seen = new java.util.HashSet<>(length());
650         return filter(t -> seen.add(keyExtractor.apply(t)));
651     }
652 
653     @Override
654     public Vector<T> drop(int n) {
655         return wrap(trie.drop(n));
656     }
657 
658     @Override
659     public Vector<T> dropUntil(Predicate<? super T> predicate) {
660         return io.vavr.collection.Collections.dropUntil(this, predicate);
661     }
662 
663     @Override
664     public Vector<T> dropWhile(Predicate<? super T> predicate) {
665         Objects.requireNonNull(predicate, "predicate is null");
666         return dropUntil(predicate.negate());
667     }
668 
669     @Override
670     public Vector<T> dropRight(int n) {
671         return take(length() - n);
672     }
673 
674     @Override
675     public Vector<T> dropRightUntil(Predicate<? super T> predicate) {
676         return io.vavr.collection.Collections.dropRightUntil(this, predicate);
677     }
678 
679     @Override
680     public Vector<T> dropRightWhile(Predicate<? super T> predicate) {
681         Objects.requireNonNull(predicate, "predicate is null");
682         return dropRightUntil(predicate.negate());
683     }
684 
685     @Override
686     public Vector<T> filter(Predicate<? super T> predicate) {
687         Objects.requireNonNull(predicate, "predicate is null");
688         return wrap(trie.filter(predicate));
689     }
690 
691     @Override
692     public <U> Vector<U> flatMap(Function<? super T, ? extends Iterable<? extends U>> mapper) {
693         Objects.requireNonNull(mapper, "mapper is null");
694         final Iterator<? extends U> results = iterator().flatMap(mapper);
695         return ofAll(results);
696     }
697 
698     @Override
699     public T get(int index) {
700         if (isValid(index)) {
701             return trie.get(index);
702         } else {
703             throw new IndexOutOfBoundsException("get(" + index + ")");
704         }
705     }
706     private boolean isValid(int index) { return (index >= 0) && (index < length()); }
707 
708     @Override
709     public T head() {
710         if (nonEmpty()) {
711             return get(0);
712         } else {
713             throw new NoSuchElementException("head of empty Vector");
714         }
715     }
716 
717     @Override
718     public <C> Map<C, Vector<T>> groupBy(Function<? super T, ? extends C> classifier) { return io.vavr.collection.Collections.groupBy(this, classifier, Vector::ofAll); }
719 
720     @Override
721     public Iterator<Vector<T>> grouped(int size) { return sliding(size, size); }
722 
723     @Override
724     public boolean hasDefiniteSize() { return true; }
725 
726     @Override
727     public int indexOf(T element, int from) {
728         for (int i = from; i < length(); i++) {
729             if (Objects.equals(get(i), element)) {
730                 return i;
731             }
732         }
733         return -1;
734     }
735 
736     @Override
737     public Vector<T> init() {
738         if (nonEmpty()) {
739             return dropRight(1);
740         } else {
741             throw new UnsupportedOperationException("init of empty Vector");
742         }
743     }
744 
745     @Override
746     public Option<Vector<T>> initOption() { return isEmpty() ? Option.none() : Option.some(init()); }
747 
748     @Override
749     public Vector<T> insert(int index, T element) { return insertAll(index, Iterator.of(element)); }
750 
751     @Override
752     public Vector<T> insertAll(int index, Iterable<? extends T> elements) {
753         Objects.requireNonNull(elements, "elements is null");
754         if ((index >= 0) && (index <= length())) {
755             final Vector<T> begin = take(index).appendAll(elements);
756             final Vector<T> end = drop(index);
757             return (begin.size() > end.size())
758                    ? begin.appendAll(end)
759                    : end.prependAll(begin);
760         } else {
761             throw new IndexOutOfBoundsException("insert(" + index + ", e) on Vector of length " + length());
762         }
763     }
764 
765     @Override
766     public Vector<T> intersperse(T element) { return ofAll(iterator().intersperse(element)); }
767 
768     /**
769      * A {@code Vector} is computed synchronously.
770      *
771      * @return false
772      */
773     @Override
774     public boolean isAsync() {
775         return false;
776     }
777 
778     @Override
779     public boolean isEmpty() { return length() == 0; }
780 
781     /**
782      * A {@code Vector} is computed eagerly.
783      *
784      * @return false
785      */
786     @Override
787     public boolean isLazy() {
788         return false;
789     }
790 
791     @Override
792     public boolean isTraversableAgain() { return true; }
793 
794     @Override
795     public Iterator<T> iterator() {
796         return isEmpty() ? Iterator.empty()
797                          : trie.iterator();
798     }
799 
800     @Override
801     public int lastIndexOf(T element, int end) {
802         for (int i = Math.min(end, length() - 1); i >= 0; i--) {
803             if (Objects.equals(get(i), element)) {
804                 return i;
805             }
806         }
807         return -1;
808     }
809 
810     @Override
811     public int length() { return trie.length(); }
812 
813     @Override
814     public <U> Vector<U> map(Function<? super T, ? extends U> mapper) {
815         Objects.requireNonNull(mapper, "mapper is null");
816         return ofAll(trie.map(mapper));
817     }
818 
819     @Override
820     public Vector<T> orElse(Iterable<? extends T> other) {
821         return isEmpty() ? ofAll(other) : this;
822     }
823 
824     @Override
825     public Vector<T> orElse(Supplier<? extends Iterable<? extends T>> supplier) {
826         return isEmpty() ? ofAll(supplier.get()) : this;
827     }
828 
829     @Override
830     public Vector<T> padTo(int length, T element) {
831         final int actualLength = length();
832         return (length <= actualLength)
833                ? this
834                : appendAll(Iterator.continually(element)
835                 .take(length - actualLength));
836     }
837 
838     @Override
839     public Vector<T> leftPadTo(int length, T element) {
840         if (length <= length()) {
841             return this;
842         } else {
843             final Iterator<T> prefix = Iterator.continually(element).take(length - length());
844             return prependAll(prefix);
845         }
846     }
847 
848     @Override
849     public Vector<T> patch(int from, Iterable<? extends T> that, int replaced) {
850         from = Math.max(from, 0);
851         replaced = Math.max(replaced, 0);
852 
853         Vector<T> result = take(from).appendAll(that);
854         from += replaced;
855         result = result.appendAll(drop(from));
856         return result;
857     }
858 
859     @Override
860     public Tuple2<Vector<T>, Vector<T>> partition(Predicate<? super T> predicate) {
861         Objects.requireNonNull(predicate, "predicate is null");
862         final ArrayList<T> left = new ArrayList<>(), right = new ArrayList<>();
863         for (int i = 0; i < length(); i++) {
864             final T t = get(i);
865             (predicate.test(t) ? left : right).add(t);
866         }
867         return Tuple.of(ofAll(left), ofAll(right));
868     }
869 
870     @Override
871     public Vector<T> peek(Consumer<? super T> action) {
872         Objects.requireNonNull(action, "action is null");
873         if (!isEmpty()) {
874             action.accept(head());
875         }
876         return this;
877     }
878 
879     @Override
880     public Vector<Vector<T>> permutations() {
881         if (isEmpty()) {
882             return empty();
883         } else if (length() == 1) {
884             return of(this);
885         } else {
886             Vector<Vector<T>> results = empty();
887             for (T t : distinct()) {
888                 for (Vector<T> ts : remove(t).permutations()) {
889                     results = results.append(of(t).appendAll(ts));
890                 }
891             }
892             return results;
893         }
894     }
895 
896     @Override
897     public Vector<T> prepend(T element) { return prependAll(io.vavr.collection.List.of(element)); }
898 
899     @Override
900     public Vector<T> prependAll(Iterable<? extends T> iterable) {
901         Objects.requireNonNull(iterable, "iterable is null");
902         if (isEmpty()) {
903             return ofAll(iterable);
904         } else {
905             final BitMappedTrie<T> that = trie.prependAll(iterable);
906             return (that == trie) ? this : new Vector<>(that);
907         }
908     }
909 
910     @Override
911     public Vector<T> remove(T element) {
912         for (int i = 0; i < length(); i++) {
913             if (Objects.equals(get(i), element)) {
914                 return removeAt(i);
915             }
916         }
917         return this;
918     }
919 
920     @Override
921     public Vector<T> removeFirst(Predicate<T> predicate) {
922         Objects.requireNonNull(predicate, "predicate is null");
923         for (int i = 0; i < length(); i++) {
924             if (predicate.test(get(i))) {
925                 return removeAt(i);
926             }
927         }
928         return this;
929     }
930 
931     @Override
932     public Vector<T> removeLast(Predicate<T> predicate) {
933         Objects.requireNonNull(predicate, "predicate is null");
934         for (int i = length() - 1; i >= 0; i--) {
935             if (predicate.test(get(i))) {
936                 return removeAt(i);
937             }
938         }
939         return this;
940     }
941 
942     @Override
943     public Vector<T> removeAt(int index) {
944         if (isValid(index)) {
945             final Vector<T> begin = take(index);
946             final Vector<T> end = drop(index + 1);
947             return (begin.size() > end.size())
948                    ? begin.appendAll(end)
949                    : end.prependAll(begin);
950         } else {
951             throw new IndexOutOfBoundsException("removeAt(" + index + ")");
952         }
953     }
954 
955     @Override
956     public Vector<T> removeAll(T element) {
957         return io.vavr.collection.Collections.removeAll(this, element);
958     }
959 
960     @Override
961     public Vector<T> removeAll(Iterable<? extends T> elements) {
962         return io.vavr.collection.Collections.removeAll(this, elements);
963     }
964 
965     @Override
966     public Vector<T> removeAll(Predicate<? super T> predicate) {
967         return io.vavr.collection.Collections.removeAll(this, predicate);
968     }
969 
970     @Override
971     public Vector<T> replace(T currentElement, T newElement) {
972         return indexOfOption(currentElement)
973                 .map(i -> update(i, newElement))
974                 .getOrElse(this);
975     }
976 
977     @Override
978     public Vector<T> replaceAll(T currentElement, T newElement) {
979         Vector<T> result = this;
980         int index = 0;
981         for (T value : iterator()) {
982             if (Objects.equals(value, currentElement)) {
983                 result = result.update(index, newElement);
984             }
985             index++;
986         }
987         return result;
988     }
989 
990     @Override
991     public Vector<T> retainAll(Iterable<? extends T> elements) {
992         return io.vavr.collection.Collections.retainAll(this, elements);
993     }
994 
995     @Override
996     public Vector<T> reverse() {
997         return (length() <= 1) ? this : ofAll(reverseIterator());
998     }
999 
1000     @Override
1001     public Vector<T> scan(T zero, BiFunction<? super T, ? super T, ? extends T> operation) {
1002         return scanLeft(zero, operation);
1003     }
1004 
1005     @Override
1006     public <U> Vector<U> scanLeft(U zero, BiFunction<? super U, ? super T, ? extends U> operation) {
1007         return io.vavr.collection.Collections.scanLeft(this, zero, operation, Iterator::toVector);
1008     }
1009 
1010     @Override
1011     public <U> Vector<U> scanRight(U zero, BiFunction<? super T, ? super U, ? extends U> operation) {
1012         return io.vavr.collection.Collections.scanRight(this, zero, operation, Iterator::toVector);
1013     }
1014 
1015     @Override
1016     public Vector<T> shuffle() {
1017         return io.vavr.collection.Collections.shuffle(this, Vector::ofAll);
1018     }
1019 
1020     @Override
1021     public Vector<T> slice(int beginIndex, int endIndex) {
1022         if ((beginIndex >= endIndex) || (beginIndex >= size()) || isEmpty()) {
1023             return empty();
1024         } else if ((beginIndex <= 0) && (endIndex >= length())) {
1025             return this;
1026         } else {
1027             return take(endIndex).drop(beginIndex);
1028         }
1029     }
1030 
1031     @Override
1032     public Iterator<Vector<T>> slideBy(Function<? super T, ?> classifier) {
1033         return iterator().slideBy(classifier).map(Vector::ofAll);
1034     }
1035 
1036     @Override
1037     public Iterator<Vector<T>> sliding(int size) {
1038         return sliding(size, 1);
1039     }
1040 
1041     @Override
1042     public Iterator<Vector<T>> sliding(int size, int step) {
1043         return iterator().sliding(size, step).map(Vector::ofAll);
1044     }
1045 
1046     @Override
1047     public Vector<T> sorted() {
1048         if (isEmpty()) {
1049             return this;
1050         } else {
1051             @SuppressWarnings("unchecked")
1052             final T[] list = (T[]) toJavaArray();
1053             Arrays.sort(list);
1054             return Vector.of(list);
1055         }
1056     }
1057 
1058     @Override
1059     public Vector<T> sorted(Comparator<? super T> comparator) {
1060         Objects.requireNonNull(comparator, "comparator is null");
1061         return isEmpty() ? this : toJavaStream().sorted(comparator).collect(collector());
1062     }
1063 
1064     @Override
1065     public <U extends Comparable<? super U>> Vector<T> sortBy(Function<? super T, ? extends U> mapper) {
1066         return sortBy(U::compareTo, mapper);
1067     }
1068 
1069     @Override
1070     public <U> Vector<T> sortBy(Comparator<? super U> comparator, Function<? super T, ? extends U> mapper) {
1071         Objects.requireNonNull(comparator, "comparator is null");
1072         Objects.requireNonNull(mapper, "mapper is null");
1073         final Function<? super T, ? extends U> domain = Function1.of(mapper::apply).memoized();
1074         return toJavaStream()
1075                 .sorted((e1, e2) -> comparator.compare(domain.apply(e1), domain.apply(e2)))
1076                 .collect(collector());
1077     }
1078 
1079     @Override
1080     public Tuple2<Vector<T>, Vector<T>> span(Predicate<? super T> predicate) {
1081         Objects.requireNonNull(predicate, "predicate is null");
1082         return Tuple.of(takeWhile(predicate), dropWhile(predicate));
1083     }
1084 
1085     @Override
1086     public Tuple2<Vector<T>, Vector<T>> splitAt(int n) {
1087         return Tuple.of(take(n), drop(n));
1088     }
1089 
1090     @Override
1091     public Tuple2<Vector<T>, Vector<T>> splitAt(Predicate<? super T> predicate) {
1092         Objects.requireNonNull(predicate, "predicate is null");
1093         final Vector<T> init = takeWhile(predicate.negate());
1094         return Tuple.of(init, drop(init.size()));
1095     }
1096 
1097     @Override
1098     public Tuple2<Vector<T>, Vector<T>> splitAtInclusive(Predicate<? super T> predicate) {
1099         Objects.requireNonNull(predicate, "predicate is null");
1100         for (int i = 0; i < length(); i++) {
1101             final T value = get(i);
1102             if (predicate.test(value)) {
1103                 return (i == (length() - 1)) ? Tuple.of(this, empty())
1104                                              : Tuple.of(take(i + 1), drop(i + 1));
1105             }
1106         }
1107         return Tuple.of(this, empty());
1108     }
1109 
1110     @Override
1111     public Vector<T> subSequence(int beginIndex) {
1112         if ((beginIndex >= 0) && (beginIndex <= length())) {
1113             return drop(beginIndex);
1114         } else {
1115             throw new IndexOutOfBoundsException("subSequence(" + beginIndex + ")");
1116         }
1117     }
1118 
1119     @Override
1120     public Vector<T> subSequence(int beginIndex, int endIndex) {
1121         Collections.subSequenceRangeCheck(beginIndex, endIndex, length());
1122         return slice(beginIndex, endIndex);
1123     }
1124 
1125     @Override
1126     public Vector<T> tail() {
1127         if (nonEmpty()) {
1128             return drop(1);
1129         } else {
1130             throw new UnsupportedOperationException("tail of empty Vector");
1131         }
1132     }
1133 
1134     @Override
1135     public Option<Vector<T>> tailOption() { return isEmpty() ? Option.none() : Option.some(tail()); }
1136 
1137     @Override
1138     public Vector<T> take(int n) {
1139         return wrap(trie.take(n));
1140     }
1141 
1142     @Override
1143     public Vector<T> takeRight(int n) {
1144         return drop(length() - n);
1145     }
1146 
1147     @Override
1148     public Vector<T> takeUntil(Predicate<? super T> predicate) {
1149         Objects.requireNonNull(predicate, "predicate is null");
1150         return takeWhile(predicate.negate());
1151     }
1152 
1153     @Override
1154     public Vector<T> takeWhile(Predicate<? super T> predicate) {
1155         Objects.requireNonNull(predicate, "predicate is null");
1156         for (int i = 0; i < length(); i++) {
1157             final T value = get(i);
1158             if (!predicate.test(value)) {
1159                 return take(i);
1160             }
1161         }
1162         return this;
1163     }
1164 
1165     /**
1166      * Transforms this {@code Vector}.
1167      *
1168      * @param f   A transformation
1169      * @param <U> Type of transformation result
1170      * @return An instance of type {@code U}
1171      * @throws NullPointerException if {@code f} is null
1172      */
1173     public <U> U transform(Function<? super Vector<T>, ? extends U> f) {
1174         Objects.requireNonNull(f, "f is null");
1175         return f.apply(this);
1176     }
1177 
1178     @Override
1179     public <T1, T2> Tuple2<Vector<T1>, Vector<T2>> unzip(Function<? super T, Tuple2<? extends T1, ? extends T2>> unzipper) {
1180         Objects.requireNonNull(unzipper, "unzipper is null");
1181         Vector<T1> xs = empty();
1182         Vector<T2> ys = empty();
1183         for (int i = 0; i < length(); i++) {
1184             final Tuple2<? extends T1, ? extends T2> t = unzipper.apply(get(i));
1185             xs = xs.append(t._1);
1186             ys = ys.append(t._2);
1187         }
1188         return Tuple.of(xs, ys);
1189     }
1190 
1191     @Override
1192     public <T1, T2, T3> Tuple3<Vector<T1>, Vector<T2>, Vector<T3>> unzip3(Function<? super T, Tuple3<? extends T1, ? extends T2, ? extends T3>> unzipper) {
1193         Objects.requireNonNull(unzipper, "unzipper is null");
1194         Vector<T1> xs = empty();
1195         Vector<T2> ys = empty();
1196         Vector<T3> zs = empty();
1197         for (int i = 0; i < length(); i++) {
1198             final Tuple3<? extends T1, ? extends T2, ? extends T3> t = unzipper.apply(get(i));
1199             xs = xs.append(t._1);
1200             ys = ys.append(t._2);
1201             zs = zs.append(t._3);
1202         }
1203         return Tuple.of(xs, ys, zs);
1204     }
1205 
1206     @Override
1207     public Vector<T> update(int index, T element) {
1208         if (isValid(index)) {
1209             return wrap(trie.update(index, element));
1210         } else {
1211             throw new IndexOutOfBoundsException("update(" + index + ")");
1212         }
1213     }
1214 
1215     @Override
1216     public Vector<T> update(int index, Function<? super T, ? extends T> updater) {
1217         Objects.requireNonNull(updater, "updater is null");
1218         return update(index, updater.apply(get(index)));
1219     }
1220 
1221     @Override
1222     public <U> Vector<Tuple2<T, U>> zip(Iterable<? extends U> that) {
1223         return zipWith(that, Tuple::of);
1224     }
1225 
1226     @Override
1227     public <U, R> Vector<R> zipWith(Iterable<? extends U> that, BiFunction<? super T, ? super U, ? extends R> mapper) {
1228         Objects.requireNonNull(that, "that is null");
1229         Objects.requireNonNull(mapper, "mapper is null");
1230         return ofAll(iterator().zipWith(that, mapper));
1231     }
1232 
1233     @Override
1234     public <U> Vector<Tuple2<T, U>> zipAll(Iterable<? extends U> that, T thisElem, U thatElem) {
1235         Objects.requireNonNull(that, "that is null");
1236         return ofAll(iterator().zipAll(that, thisElem, thatElem));
1237     }
1238 
1239     @Override
1240     public Vector<Tuple2<T, Integer>> zipWithIndex() {
1241         return zipWithIndex(Tuple::of);
1242     }
1243 
1244     @Override
1245     public <U> Vector<U> zipWithIndex(BiFunction<? super T, ? super Integer, ? extends U> mapper) {
1246         Objects.requireNonNull(mapper, "mapper is null");
1247         return ofAll(iterator().zipWithIndex(mapper));
1248     }
1249 
1250     private Object readResolve() { return isEmpty() ? EMPTY : this; }
1251 
1252     @Override
1253     public boolean equals(Object o) {
1254         return io.vavr.collection.Collections.equals(this, o);
1255     }
1256 
1257     @Override
1258     public int hashCode() {
1259         return io.vavr.collection.Collections.hashOrdered(this);
1260     }
1261 
1262     @Override
1263     public String stringPrefix() { return "Vector"; }
1264 
1265     @Override
1266     public String toString() { return mkString(stringPrefix() + "(", ", ", ")"); }
1267 }
1268 
1269 interface VectorModule {
1270     final class Combinations {
1271         static <T> Vector<Vector<T>> apply(Vector<T> elements, int k) {
1272             return (k == 0)
1273                    ? Vector.of(Vector.empty())
1274                    : elements.zipWithIndex().flatMap(
1275                     t -> apply(elements.drop(t._2 + 1), (k - 1)).map((Vector<T> c) -> c.prepend(t._1)));
1276         }
1277     }
1278 }